package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理订单超时
     */
    @Scheduled(cron = "0 * * * * ?")  //每分钟执行一次
    public void OrderOutTime(){
        log.info("订单超时{}", LocalDateTime.now());
        //处理超出事件范围
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> orders = orderMapper.getOutTimeOrder(Orders.PENDING_PAYMENT,time);
        if(orders!=null && orders.size()>0){
            for (Orders order:orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单超时");
                orderMapper.update(order);
            }
        }
    }

    /**
     * 处理派送中超时
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void DeliveryOutTime(){
        log.info("处理派送中任务超时{}", LocalDateTime.now());
        //处理超出事件范围
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> orders = orderMapper.getOutTimeOrder(Orders.DELIVERY_IN_PROGRESS,time);
        if(orders!=null && orders.size()>0){
            for (Orders order:orders) {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }
    }
}
